//
//  Status.m
//  微博2期
//
//  Created by J on 15/11/28.
//
//

#import "Status.h"
#import "MJExtension.h"
#import "Photo.h"
#import "RegexKitLite.h"
#import "User.h"
#import "TextPart.h"
#import "Emotion.h"
#import "EmotionTool.h"//读取表情工具类

@implementation Status


- (NSDictionary *)objectClassInArray{
    return @{@"pic_urls":[Photo class]};
}

/**
 *  普通文字 -- > 属性文字
 *
 *  @param text 普通文字
 *
 *  @return 属性文字
 */
- (NSAttributedString*)attributedTextWithText:(NSString*)text{
        //利用text生成attributedText
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]init];
    //    [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(0, 5)];
    
    NSString* emotionPattern = @"\\[[\\u4e00-\\u9fa5]+\\]";//只要是中文就找出来
    
    //#话题#规则
    NSString* atPattern = @"#[0-9a-zA-Z\\u4e00-\\u9fa5-_]+#";//头尾#中间数字 字母汉字都行
    
    //        |匹配多个条件 相当于or \或
    NSString* topicPattern = @"\\[[\\u4e00-\\u9fa5]+\\]|@[0-9a-zA-Z\\u4e00-\\u9fa5]+|#[0-9a-zA-Z\\u4e00-\\u9fa5]+";//头尾#中间数字 字母汉字都行
    
    NSString* urlPattern = @"((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";//头尾#中间数字 字母汉字都行 0个或者一个s
    
    NSString* pattern = [NSString stringWithFormat:@"%@|%@|%@|%@",emotionPattern,atPattern,topicPattern,urlPattern];
    
    NSMutableArray * parts = [NSMutableArray array];
    //遍历所有特殊字符串
    [text enumerateStringsMatchedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        
//        //        NSLog(@"%@ %@",*capturedStrings,NSStringFromRange(*capturedRanges));
//        [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:*capturedRanges];
        TextPart* part = [[TextPart alloc]init];
        part.special = YES;
        part.text = * capturedStrings;
        part.emotion = [part.text hasPrefix:@"["]&&[part.text hasSuffix:@"]"];
        part.range = *capturedRanges;
        [parts addObject:part];
        
    }];
    
    
    //找出所有正则表达式范围相反部分  遍历所有非特殊字符
    [text enumerateStringsSeparatedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        if ((*capturedRanges).length==0)return;
        
        TextPart* part = [[TextPart alloc]init];
        part.text = * capturedStrings;
        part.range = *capturedRanges;
        [parts addObject:part];

    }];
    
//    NSLog(@"%@",parts);
    //排序 系统默认按照从小到大顺序排列对象
    [parts sortedArrayUsingComparator:^NSComparisonResult(TextPart *  part1, TextPart *  part2) {
//        NSOrderedAscending (生序, part1 < part2 ) NSOrderedSame(一样大), NSOrderedDescending(part1>part2)
       
        if (part1.range.location > part2.range.location) {
//            part1>part2
//            part1放后面 part2放前面
            return NSOrderedDescending;
        }
        //            part1 < part2
        //            part1放前面 part2放后面

        return NSOrderedAscending;
    }];
    
    UIFont * font = [UIFont systemFontOfSize:15];
    //排序拼接每一段文字
    for (TextPart* part in parts) {
        NSAttributedString* substr = nil;//等会儿需要拼接的子串
        if (part.isEmotion) {
            NSTextAttachment * attch = [[NSTextAttachment alloc]init];
            NSString * name = [EmotionTool emotionWithChs:part.text].png;//根据表情文字 拿到表情对象
            attch.image = [UIImage imageNamed:name];
            attch.bounds = CGRectMake(0, -3, font.lineHeight, font.lineHeight);
            substr =  [NSAttributedString attributedStringWithAttachment:attch];
            if (!name) {//表情文字不存在
                substr = [[NSAttributedString alloc] initWithString:part.text];
            }
        }else if (part.special){//非表情的特殊文字
      substr =  [[NSAttributedString alloc] initWithString:part.text attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}];
        }else{//非特殊文字
            substr = [[NSAttributedString alloc] initWithString:part.text];
        }
    
        [attributedText appendAttributedString:substr];

    }
    //一定要设置字体 保证计算出来的尺寸是正确的
    [attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
    
    return attributedText;
}
- (void)setText:(NSString *)text{
    _text = [text copy];
   
  self.attributedText = [self attributedTextWithText:text];
    //    NSLog(@"%@",text);
}

- (NSString *)created_at{
    /**
     1.今年
     1> 今天  刚刚1分钟内   xx分钟前1分钟->59分钟内发的   60分钟 > xx小时前
     2> 昨天
     3> 其他  月份日期
     2.非今年
     1> xxxx-xx-xx xx:xx    * 年月日
     */
//    Fri Dec 04 21:57:20 +0800 2015
    // NSString --> NSDate
    NSDateFormatter * fm =[[NSDateFormatter alloc]init];
    //如果是真机调试 转换这种欧美时间需要设置locale
    fm.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    //设置日期格式(声明字符串里面每个数组和单词的含义)
    //E:星期几
    //M:月份
    //d:日期（这个月第几天）
    //H:24小时制 小时
    //m:分钟
    //s:秒
    //y:年
    fm.dateFormat = @"EEE  MM dd HH:mm:ss Z yyyy";
    //微博创建日期
    NSDate * createDate = [fm dateFromString:_created_at];//先把创建时间字符串转换成时间
    fm.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    //当前时间
    NSDate * now =[NSDate date];
    //日历对象 （方便比较两个日期的差距)
    NSCalendar * calendar = [NSCalendar currentCalendar];
//枚举代表想获得哪些差值
    NSCalendarUnit unit =NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond ;
    //计算两个日期之间的差距
    NSDateComponents *cmps = [calendar components:unit fromDate:now toDate:createDate options:0];//哪个写前面 后面都不影响结果
    //获得某个时间的年月日 时分秒
    
    if ([createDate isThisYear]) {//今年
        if ([createDate isYesterday]) {//昨天
            fm.dateFormat = @"昨天 HH:mm";
            return [fm stringFromDate:createDate];
        }else if([createDate isToday]){//今天
            if (cmps.hour>=1) {
                return [NSString stringWithFormat:@"%zd小时前",cmps.hour];
            }else if(cmps.minute>=1)//一个小时内
            {
                return [NSString stringWithFormat:@"%zd分钟前",cmps.minute];
            }else{//1分钟内
                return [NSString stringWithFormat:@"刚刚"];
            }

        }else{//今年的其它日子
            fm.dateFormat = @"MM-dd HH:mm";
            return [fm stringFromDate:createDate];
        }
    
    }else{//非今年
    fm.dateFormat = @"yyyy-MM-dd HH:mm";
    return [fm stringFromDate:createDate];
    }
    
}

//    2015-12-05 14:19:24.708 微博2期[36826:3554003] <a href="http://app.weibo.com/t/feed/1tqBja" rel="nofollow">360安全浏览器</a>
- (void)setSource:(NSString *)source{
    NSRange range ;
    if (source.length) {
        range.location = [source rangeOfString:@">"].location+1;
        range.length = [source rangeOfString:@"<" options:NSBackwardsSearch].location-1 - [source rangeOfString:@">"].location;
        _source = [NSString stringWithFormat:@"来自 %@",[source substringWithRange:range]];
    }

    //截取字符串
}


- (void)setRetweeted_status:(Status *)retweeted_status{
    
    _retweeted_status = retweeted_status;
    
    NSString * retweetContent = [NSString stringWithFormat:@"@%@ : %@",retweeted_status.user.name,retweeted_status.text];
    self.retweetedAttributedText = [self attributedTextWithText:retweetContent];
    
    
    
}




@end
